﻿
using DataWasher.WebApi.Interfaces;
using DataWasher.WebApi.Models;
using DataWasher.WebApi.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ToolManager.Entities;
using Microsoft.Azure.Cosmos.Table;
using ToolManager.IService;
using ToolManager.Common;
using Microsoft.Azure.Documents.SystemFunctions;

namespace DataWasher.WebApi.Services
{
    public class DataExtractService : IDataExtractService
    {
        public readonly ICostRecordRepository _costRecordRep;
        public readonly IVmMntrRequestDetailRepository _vmRequestDetailRep;
        public readonly IStorageService _storageService;
        public DataExtractService(ICostRecordRepository costRecordRep, IVmMntrRequestDetailRepository vmRequestDetailRep, IStorageService storageService)
        {
            _costRecordRep = costRecordRep;
            _vmRequestDetailRep = vmRequestDetailRep;
            _storageService = storageService;
        }
        /// <summary>
        /// 清洗业务数据
        /// </summary>
        /// <returns></returns>
        public async Task<bool> Extract()
        {
            try
            {
                //获取目标数据的总页数，每页100条
                var pages = (await _vmRequestDetailRep.GetSourceDataCount()) / 50 + 1;
                var pageDatas = new List<SourceData>();
                TableBatchOperation tableBatchOperation = null;
                //逐页处理，插入storage
                for (int index = 0; index < pages; index++)
                {
                    //获取当前页数据
                    pageDatas = await _vmRequestDetailRep.GetSourceDataPaged(index);
                    //将当前页数据转化为storage 批量插入的对象
                    tableBatchOperation = await TranslateEntity(pageDatas);
                    //将批量对象插入storage
                    await _storageService.InsertBatchData(tableBatchOperation, "Businessdata");
                    //System.Threading.Thread.Sleep(2 * 1000);
                }

            }
            catch (Exception ex)
            {

                throw ex;
            }

            return true;
        }

        public async Task<TableBatchOperation> TranslateEntity(List<SourceData> sourceDatas)
        {
            var busDataList = new List<BusinessDataEntity>();
            var tableBatchOperation = new TableBatchOperation();
            BusinessDataEntity busData = null;
            var partionKey = DateTime.Now.ToString("yyyyMMdd");

            sourceDatas.ForEach(x =>
            {
                //在批量对象中逐个插入entity，partitionkey是当前日期,
                //这样清理storage里的数据的时候可以按照日期清理
                busData = new BusinessDataEntity(partionKey)
                {
                    AcceptanceDate = (x.AcceptanceDate == null ? string.Empty : x.AcceptanceDate?.ToString("yyyy-MM-dd")),
                    AddDate = (x.AddDate == null ? 0 : int.Parse(x.AddDate?.ToString("yyyyMMdd"))),
                    AddDateYear = (int)(x.AddDate == null ? 0 : x.AddDate?.Year),
                    AddDateMonth = (int)(x.AddDate == null ? 0 : x.AddDate?.Month),
                    AddDateDay = (int)(x.AddDate == null ? 0 : x.AddDate?.Day),
                    AddDateYM = (x.AddDate == null ? 0 : int.Parse(x.AddDate?.ToString("yyyyMM"))),
                    ApproveDate = (x.ApproveDate == null ? string.Empty : x.ApproveDate?.ToString("yyyy-MM-dd")),
                    ApproveFlowDate = (x.ApproveFlowDate == null ? string.Empty : x.ApproveFlowDate?.ToString("yyyy-MM-dd")),
                    CompleteDate = (x.CompleteDate == null ? 0 : int.Parse(x.CompleteDate?.ToString("yyyyMMdd"))),
                    Cost = x.Cost.ToString(),
                    Settlement = x.Settlement.ToString(),
                    FinishedTime = (x.FinishedTime == null ? string.Empty : x.FinishedTime?.ToString("yyyy-MM-dd")),
                    MntCategory = x.MntCategory,
                    MntStatus = x.MntStatus,
                    Score = x.Score ?? 0,
                    StoreName = x.StoreName,
                    TaskingDate = (x.TaskingDate == null ? string.Empty : x.TaskingDate?.ToString("yyyy-MM-dd")),
                    UpdateDate = (x.UpdateDate == null ? string.Empty : x.UpdateDate?.ToString("yyyy-MM-dd")),
                    ValidDate = (x.ValidDate == null ? 0 : int.Parse(x.ValidDate?.ToString("yyyyMMdd"))),
                    VendorName = x.VendorName,
                    VendorOwnerName = x.VendorOwnerName,
                    OrderAddDate = (x.OrderAddDate == null ? string.Empty : x.OrderAddDate?.ToString("yyyy-MM-dd")),
                    Score1 = x.Score1 ?? 0,
                    Score2 = x.Score2 ?? 0,
                    DomainTag = x.DomainTag ?? string.Empty,
                    ParentDomainId = x.ParentDomainId ?? string.Empty,
                    BrandNameCn = x.BrandNameCn ?? string.Empty,
                    DomainId = x.DomainId ?? string.Empty,
                    DomainName = x.DomainName ?? string.Empty,
                    StoreIdBase = x.StoreIdBase ?? string.Empty,
                    StoreNameBase = x.StoreNameBase ?? string.Empty,
                    TagName = x.TagName ?? string.Empty,
                    TypeName = x.TypeName ?? string.Empty,
                    MntCategory2 = x.MntCategory2 ?? string.Empty,
                    Language = x.Language,
                    CostType = x.CostType,
                    Priority = x.Priority,
                    ProblemIds = x.ProblemIds ?? string.Empty

                };
                tableBatchOperation.InsertOrReplace(busData);
            });
            return tableBatchOperation;
        }

        /// <summary>
        /// 提取筛选器数据
        /// </summary>
        /// <returns></returns>
        public async Task<bool> ExtractFilterData()
        {
            //插入前先删除
            await _storageService.DeleteTableAsync("Priority");
            await _storageService.DeleteTableAsync("TagName");
            await _storageService.DeleteTableAsync("MntCategory");
            //等待storage table中的数据删除
            System.Threading.Thread.Sleep(60 * 1000);

            //分别从mysql获取 店铺标签，维修类别，优先级，然后写入stroage table
            var tagNameEntityList = await _vmRequestDetailRep.GetTagNamesDatas();
            await InsertIntoStorage<TagNameEntity>(tagNameEntityList, "TagName");

            var categoryEntityList = await _vmRequestDetailRep.GetCategoryDatas();
            await InsertIntoStorage<MntCategoriesEntity>(categoryEntityList, "MntCategory");

            var priorityEntityList = await _vmRequestDetailRep.GetPriorityDatas();
            await InsertIntoStorage<PriorityEntity>(priorityEntityList, "Priority");

            return true;

        }

        public async Task<bool> InsertIntoStorage<T>(IList<T> objData, string TableName) where T : class
        {
            TableBatchOperation tabBatchOperation = null;
            var pages = objData.Count() / 100 + 1;
            var tempData = new List<T>();
            for (int index = 0; index < pages; index++)
            {
                tabBatchOperation = new TableBatchOperation();
                tempData = objData.Skip(index * 100).Take(100).ToList();
                foreach (var tem in tempData)
                {
                    tabBatchOperation.InsertOrReplace((ITableEntity)Convert.ChangeType(tem, typeof(T)));
                }
                await _storageService.InsertBatchData(tabBatchOperation, TableName);
            }
            return true;
        }

        public async Task<bool> ExtracProblemData()
        {
            var proEntityList = new List<ProblemEntity>();
            var paritionKey = DateTime.Now.ToString("yyyyMMdd");
            var proList = await _vmRequestDetailRep.GetProblemData();
            proList.ForEach(x =>
            {
                proEntityList.Add(new ProblemEntity(paritionKey)
                {
                    Content = x.Content,
                    MpId = x.MpId,
                    Language = x.Language
                });
            });

            await InsertIntoStorage<ProblemEntity>(proEntityList, "Problem");

            return true;
        }

    }
}
